<?php defined('SYSPATH') or die('No direct script access.');

class Signup_Controller extends PublicController {

    public function __construct() {
        parent::__construct();
    }

    /**
     * Default action method.
     */
    public function index() {
        return $this->createForm();
    }

    public function createForm() {
        $this->viewData['formData'] = array(
        		'preferred_language' => Router::$language
        );
        $this->accountFormData();
        $this->renderSubview('signUp/signUpForm');
    }

    public function accountFormData() {
        $this->viewData['countryOptions'] = $this->dao->optionsCountry(true);
        $this->viewData['idcardTypeOptions'] = form::idcardOptions();
        $this->viewData['organizationOptions'] = $this->dao->optionsOrganizationsByCountry();
    }

    public function create() {
        $formData = $this->postToDbValues();

        $this->viewData['formData'] = $formData;

        // Robot detection
        if ($formData['is_robot'] != 'no') {
            $this->redirect('/');
        }
        unset($formData['is_robot']);

        // Basic validation
        $validator = new EntityValidator($formData, 'person', $this->msg);
        $validator->required('login');
        $validator->minLength('password', 5);

        $validator = new EntityValidator($formData, 'person', $this->msg);
        $validator->required('first_name');
        $validator->required('last_name');
        $validator->required('gender');
        $validator->date('birth_date');
        $validator->required('street');
        $validator->required('city');
        $validator->required('postal_code');
        $validator->required('country_code');
        $validator->required('country_of_residence_code');
        $validator->required('email');
        $validator->idOrNull('organization_id');
        $validator->applicationLanguage('preferred_language');
        if (valid::isIsoDate($formData['birth_date'])) {
        	if (seminarHelper::arePapersRequired($formData['birth_date'])) {
        		$validator->required('idcard_type');
        		$validator->required('idcard_number');
        	}
        }

        if ($formData['personalDataAgreement'] != sql::$TRUE) {
            $this->msg->error('signUp.mustAgreeWithDataProcessing');
        }
        unset($formData['personalDataAgreement']);
        
        if ($this->msg->hasErrors()) {
            $this->accountFormData();
            $this->renderSubview('signUp/signUpForm');
            return;
        }

        $this->dao->getDb()->beginTransaction();
        try {
            // Database validation
        	if ($formData['organization_id']) {
        		$organization = $this->dao->getById('organization', $formData['organization_id']);
        		if (! $organization) {
        			$this->msg->error('error-recordNotFound');
        			$this->loadFormData();
        			$this->renderSubview('signUp/signUpForm');
        			return;
        		}
        	}
        	
            $uniqueFields = array ('first_name', 'last_name', 'birth_date');
            $existingAccount = $this->dao->getUniqueByFieldsOfEntity('person', $formData, $uniqueFields);
            if ($existingAccount) {
                // Read all person+account properties
                $existingAccount = $this->dao->fetchPersonById($existingAccount['id']);
                // If the existing person without an account, create only the account for the already existing person.
                if (! $existingAccount['login']) {
                    $person = $this->dao->getById('person', $existingAccount['id']);
                }
                else {
                    $this->accountFormData();
                    $this->msg->error('signUp.userAlreadyExists');
                    $this->viewData['lostPasswordLogin'] = $existingAccount['login'];
                    $this->renderSubview('signUp/signUpForm');
                    return;
                }
            }

            if ($this->dao->alreadyExists('account', 'login', $formData, 'person_id')) {
                $this->accountFormData();
                $this->msg->error('person.error-alreadyExists-login', $formData['login']);
                $this->renderSubview('signUp/signUpForm');
                return;
            }

            // Insert or update the person
            if ($person) {
                $personId = $person['id'];
                $person = array_merge($person, $formData);
                $this->dao->update('person', $person, 'id', array('login', 'password'));
            }
            else {
                // Create person and account records in the DB
                $personId = $this->dao->insert('person', $formData, array('login', 'password'));
            }

            $account = array(
                'person_id' => $personId,
                'login'     => $formData['login'],
                'password'  => auth::passwordHash($formData['login'], $formData['password']),
                'is_admin'  => sql::$FALSE,
                'is_blocked' => sql::$FALSE
            );
            $this->dao->insert('account', $account);
            $this->dao->getDb()->commit();
        }
        catch (Exception $e) {
            $this->dao->getDb()->rollBack();
            $this->msg->error('error.dbException', $e->getCode());
            Kohana::log('error', $e);
            $this->redirect('/');
        }

        if ($person) {
            $this->msg->info('signUp.usingExistingPerson');
        }
        $this->msg->info('signUp.success');

        // Send a confirmation email to the user.
        $emailBody = text::getInLang($formData['preferred_language'], 'signUp.confirmationEmail-body', $formData['login']);
        $mailResult = email::sendInUtf8(
                $formData['first_name'] . ' ' . $formData['last_name'],
                $formData['email'],
                text::getInLang($formData['preferred_language'], 'signUp.confirmationEmail-title'),
                email::addHeadingAndClosing($emailBody, $person, $formData['preferred_language']));
        if (! $mailResult) {
            $this->msg->warning('viregWizard.mailFailedRegistrationValid');
        }

        $person = $this->dao->fetchPersonByLogin($formData['login']);
        $this->getSessionData()->setAuthUser($person);

        $this->redirectWithLanguage('/user/userSpace', $person['preferred_language']);
    }

    public function personalDataAgreement() {
        $this->renderSubview('/signUp/personalDataAgreement');
    }
}